<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>登录</button>
    <button>看大海</button>

    <script>
        let btns = document.querySelectorAll('button');

        btns[0].onclick = function () {
            let xhr = new XMLHttpRequest();

            xhr.open('post', 'http://localhost:8888/login');

            // 允许跨域请求携带凭证：cookie
            // xhr.withCredentials = true;

            xhr.onload = function () {
                console.log(this.responseText);
                console.log(this.getResponseHeader('Authorization'));

                // 选择一个本地存储，存放token
                localStorage.setItem('auth', this.getResponseHeader('Authorization'));
            }

            xhr.send();
        }

        btns[1].onclick = function() {
            let xhr = new XMLHttpRequest();

            xhr.open('get', 'http://localhost:8888/dahai');

            // 允许跨域请求携带凭证：cookie
            // xhr.withCredentials = true;

            xhr.onload = function () {
                console.log(this.responseText);
            }

            let token = localStorage.getItem('auth');
            if (token) {
                xhr.setRequestHeader('Authorization', token);
            }

            xhr.send();
        }
    </script>
</body>

</html>
